var actions = function(a) {
	this.apply = this.revert = this.save = function(e) {
		var b = $(e.target),
			a = b.attr('action'),
			f = $(e.target.form),
			url = (f.attr('action') ? f.attr('action') + '/' : ''  )  + a,
			r = /\W+/g,
			data = f.serializeArray();
		
		$.ajax({
			url : url,
			type : f.attr('method') || 'POST',
			dataType : 'json',
			data : data,
			success : function (result, code, xhr) {
				if (!result.success) {
					alert(result.error);
					return;
				}
				if(a == 'save') {
					window.history.back();
				} else {
					for(var k in result.data) {
						f.find('[name=' + k + ']').val(result.data[k]);
					}
				}
			}
		});
	};
	
	this.cancel = function(e) {
		window.history.back();
	};
	
	this.error = function() {
		$.error('Undefined action: ' + a);
	};

	return $.proxy(this[a] ? this[a] : this.error, this);
};

$(document).ready(function() {
	$('textarea.wysiwyg').ckeditor({});

	$('.form-actions button').each(function (index, btn) {
		btn = $(btn);
		btn.click(actions(btn.attr('action')));
	});
});

